import vue from '@vitejs/plugin-vue';
import vueJSX from '@vitejs/plugin-vue-jsx';
import { resolve } from 'path';
import UnoCSS from 'unocss/vite';
import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import { ViteEjsPlugin } from 'vite-plugin-ejs';
import { ElementPlusResolve, createStyleImportPlugin } from 'vite-plugin-style-import';
import ViteYaml from '@modyfi/vite-plugin-yaml';

const root = process.cwd();
function pathResolve(dir: string) {
  return resolve(root, '.', dir);
}

const getElementPlusStyles = (useAllStylesStr: string) => {
  const useAllElementPlusStyle = useAllStylesStr === 'false';

  // 如果不使用全部组件，不需要导入样式, 只导入使用到的组件的样式
  if (useAllElementPlusStyle) {
    return createStyleImportPlugin({
      resolves: [ElementPlusResolve()],
      libs: [
        {
          libraryName: 'element-plus',
          esModule: true,
          resolveStyle: (name) => {
            if (name === 'click-outside') {
              return '';
            }
            return `element-plus/es/components/${name.replace(/^el-/, '')}/style/css`;
          }
        }
      ]
    });
  }
};
export default ({ command, mode }: ConfigEnv): UserConfig => {
  let env: Record<string, string> = {};
  const isBuild = command === 'build';
  if (!isBuild) {
    env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root);
  } else {
    env = loadEnv(mode, root);
  }
  
  return {
    base: env.VITE_BASE_PATH,
    plugins: [
      vue({
        script: {
          // 开启defineModel
          defineModel: true
        }
      }),
      // 开启vue的jsx支持
      vueJSX(),
      getElementPlusStyles(env.VITE_USE_ALL_ELEMENT_PLUS_STYLE),
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      }),
      UnoCSS(),
      ViteYaml()
    ],
    css: {
      preprocessorOptions: {
        less: {
          additionalData: '@import "./src/styles/variables.module.less";',
          javascriptEnabled: true
        }
      }
    },
    resolve: {
      // prettier-ignore
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
      alias: [
        {
          find: /@\//,
          replacement: `${pathResolve('src')}/`
        }
      ]
    }
  };
};
